#!/usr/bin/python
# coding: utf-8

import requests
import time
import json
import socket

DEBUG = True
WORKER_SWITCH = False

SCHEME = "http"
URL_HEADER = SCHEME + "://"
MASTER_HOST = "127.0.0.1"
MASTER_PORT = "19999"
METRICS_PATH = "/metrics/json/"
WORKER_LIST_PATH = "/api/v1/master/worker_info_list/"
FALCON_PUSH_URL = "http://127.0.0.1:1988/v1/push"
PREFIXS = ["client", "master", "worker"]

hostname = socket.gethostname()
ts = int(time.time())


def convert(decoded, host, output):
    for k, v in decoded["gauges"].iteritems():
        role = "default"
        prefix, str2 = k.split('.', 1)
        if prefix in PREFIXS:
            role = prefix
        elem = {
            "endpoint": hostname,
            "metric": k + "-metric",
            "timestamp": ts,
            "step": 60,
            "value": v["value"],
            "counterType": "GAUGE",
            "tags": "host=" + host + ",role=" + role,
        }
        output.append(elem)
    for k, v in decoded["counters"].iteritems():
        role = "default"
        prefix, str2 = k.split('.', 1)
        if prefix in PREFIXS:
            role = prefix
        elem = {
            "endpoint": hostname,
            "metric": k + "-metric",
            "timestamp": ts,
            "step": 60,
            "value": v["count"],
            "counterType": "COUNTER",
            "tags": "role=" + role,
        }
        output.append(elem)
    return output


def getRequestUrl(host, port, path):
    return URL_HEADER + host + ":" + str(port) + path


def requestAndGenOutput(host, port, output):
    metricsUrl = getRequestUrl(host, port, METRICS_PATH)
    result = requests.get(metricsUrl)
    if result.status_code == 200:
        decoded = json.loads(result.content)
        convert(decoded, host, output)
        return result.status_code
    else:
        print("[%d]", result.status_code)
        return result.status_code


def main():
    """
    从master请求worker列表，再请求worker和master的metrics信息，转换为falcon的请求参数json，然后发送请求给falcon
    :return: status code.
    """
    output = []
    status_code = 0
    if WORKER_SWITCH:
        result = requests.get(getRequestUrl(MASTER_HOST, MASTER_PORT, WORKER_LIST_PATH))
        if result.status_code == 200:
            workerListJson = json.loads(result.content)
            for workerJson in workerListJson:
                workerHost = workerJson["address"]["host"]
                workerPort = workerJson["address"]["webPort"]
                status_code = requestAndGenOutput(workerHost, workerPort, output)
                if status_code != 200:
                    return status_code
    status_code = requestAndGenOutput(MASTER_HOST, MASTER_PORT, output)
    if status_code != 200:
        return status_code

    # 如果都成功才会到这里
    tofalcon = json.dumps(output)
    if DEBUG:
        print json.dumps(output, indent=1)
        print "total count = %d" % len(output)
    else:
        r = requests.post(FALCON_PUSH_URL, tofalcon)
        print r.text
        status_code = r.status_code
    return status_code


if __name__ == '__main__':
    main()
